package com.hellobike.haxing.modules.wms.controller;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.wms.dto.*;
import com.hellobike.haxing.modules.wms.entity.PickHeader;
import com.hellobike.haxing.modules.wms.entity.PickTask;
import com.hellobike.haxing.modules.wms.enums.PickTypeEnum;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsDeliveryFacade;
import com.hellobike.haxing.modules.wms.service.IPickHeaderService;
import com.hellobike.haxing.modules.wms.service.IPickTaskService;
import com.hellobike.haxing.modules.wms.utils.FileUtil;
import com.hellobike.haxing.modules.wms.utils.HtmlToPdf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: t_wms_pick_header
 * @Author: haxing-boot
 * @Date: 2020-01-14
 * @Version: V1.0
 */
@RestController
@RequestMapping("/wms/pickHeader")
@Slf4j
public class PickHeaderController extends WmsBaseController<PickHeader, IPickHeaderService> {
    @Autowired
    private IPickHeaderService pickHeaderService;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 分页列表查询
     *
     * @param pickHeader
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "t_wms_pick_header-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(PickHeader pickHeader,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        pickHeader.setWarehouseId(getWarehouseId());
        QueryWrapper<PickHeader> queryWrapper = QueryGenerator.initQueryWrapper(pickHeader, req.getParameterMap());
        Page<PickHeader> page = new Page<PickHeader>(pageNo, pageSize);
        page.addOrder(OrderItem.desc("id"));
        IPage<PickHeader> pageList = pickHeaderService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param pickHeader
     * @return
     */
    @AutoLog(value = "t_wms_pick_header-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody PickHeader pickHeader) {
        pickHeaderService.save(pickHeader);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param pickHeader
     * @return
     */
    @AutoLog(value = "t_wms_pick_header-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody PickHeader pickHeader) {
        pickHeaderService.updateById(pickHeader);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "t_wms_pick_header-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        pickHeaderService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "t_wms_pick_header-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.pickHeaderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        PickHeader pickHeader = pickHeaderService.getById(id);
        if (pickHeader == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(pickHeader);
    }


    /**
     * 导出excel
     */
    @AutoLog(value = "t_wms_pick_header-导出pdf", operateType = 6)
    @RequestMapping(value = "/download")
    public void download(@RequestParam String idStr, HttpServletResponse response) throws WmsServiceException, WmsExportException {
        try {
            String filename = RandomStringUtils.random(12, false, true) + ".pdf";
            String type = new MimetypesFileTypeMap().getContentType(filename);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type", type);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            Context context = new Context();  //thymeleaf包下的
            Map<String, Object> map = new HashMap<>();
            List<ExportPickPrintDto> list = wmsExportFacade.exportPickInfo(idStr);
            Map<String, ExportPickPrintDto> exportPickPrintDtoMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(list)) {
                for (ExportPickPrintDto exportPickPrintDto : list) {
                    if (!exportPickPrintDtoMap.containsKey(exportPickPrintDto.getShopName())) {
                        exportPickPrintDtoMap.put(exportPickPrintDto.getShopName(), exportPickPrintDto);
                    }
                    ExportPickPrintDto first = exportPickPrintDtoMap.get(exportPickPrintDto.getShopName());
                    /**
                     * 把后面的 do 单合到前面
                     */
                    if (!exportPickPrintDto.getDoCode().equals(first.getDoCode())) {
                        if (!CollectionUtils.isEmpty(exportPickPrintDto.getPoList())) {
                            for (ExportPicPrintDetailDto exportPicPrintDetailDto : exportPickPrintDto.getPoList()) {
                                boolean isNew = true;
                                for (ExportPicPrintDetailDto picPrintDetailDto : first.getPoList()) {
                                    if (picPrintDetailDto.getBarcode().equals(exportPicPrintDetailDto.getBarcode())) {
                                        isNew = false;
                                        if (picPrintDetailDto.getPickQty() == null) {
                                            picPrintDetailDto.setPickQty(BigDecimal.ZERO);

                                        }
                                        if (exportPicPrintDetailDto.getPickQty() == null) {
                                            exportPicPrintDetailDto.setPickQty(BigDecimal.ZERO);
                                        }
                                        picPrintDetailDto.setQty(exportPicPrintDetailDto.getQty() + picPrintDetailDto.getQty());
                                        picPrintDetailDto.setPickQty(exportPicPrintDetailDto.getPickQty().add(picPrintDetailDto.getPickQty()));
                                    }
                                }
                                if (isNew) {
                                    first.getPoList().add(exportPicPrintDetailDto);
                                }
                            }
                        }
                    }
                }
            }
            log.info("{}", JSON.toJSONString(list));
            map.put("shopPoList", exportPickPrintDtoMap.values());
            context.setVariables(map);
            String html = templateEngine.process("pick_print", context);
            try {
                log.info(html);
                HtmlToPdf.topdf(html, "/tmp/" + filename);
                FileUtil.download("/tmp/" + filename, response);
            } catch (Exception ex) {
                log.error("", ex);
            }
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 导出excel
     */
    @AutoLog(value = "t_wms_pick_header-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(@RequestParam Long id) throws WmsServiceException, WmsExportException {
        try {
            String title = "";
            PickHeader pickHeader = pickHeaderService.getById(id);
//            List<PickTask> pickTasks = pickTaskService.getByDocOperId(pickHeader.getId());
            if (PickTypeEnum.KQ.getValue().equals(pickHeader.getPickType())) {
                title = "库区拣货-" + pickHeader.getStoreType() + "-" + pickHeader.getDocNo();
                List<ExportPickKQDto> exportList = wmsExportFacade.exportPickKQ(id);
                return export(title, ExportPickKQDto.class, exportList);
            } else if (PickTypeEnum.ZTD.getValue().equals(pickHeader.getPickType())) {
                title = "自提点拣货-" + pickHeader.getDocNo();
                List<ExportPickZTDDto> exportList = wmsExportFacade.exportPickZTD(id);
                return export(title, ExportPickZTDDto.class, exportList);
            }
            throw new WmsServiceException("暂不支持的拣货单");
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "t_wms_pick_header-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PickHeader.class);
    }

    @Autowired
    private WmsDeliveryFacade wmsDeliveryFacade;
    @Autowired
    private IPickTaskService pickTaskService;

    @AutoLog(value = "t_wms_pick_header-queryPickTask", operateType = 5)
    @RequestMapping(value = "/queryPickTask", method = RequestMethod.POST)
    public Result<?> queryPickTask(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        Long pickHeaderId = param.getLong("pickHeaderId");
        List<PickTaskDto> tasks = null;
        try {
            tasks = wmsDeliveryFacade.queryPickTask(pickHeaderId);
        } catch (WmsServiceException e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok(tasks);
    }


    @AutoLog(value = "t_wms_pick_header-pickWaveTask", operateType = 5)
    @RequestMapping(value = "/pickWaveTask", method = RequestMethod.POST)
    public Result<?> pickWaveTask(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        try {
            Long pickHeaderId = param.getLong("pickHeaderId");
            String opName = param.getString("opName");
            List<PickTask> tasks = JSON.parseArray(param.getJSONArray("data").toJSONString(), PickTask.class);
            wmsDeliveryFacade.pickWavePickTask(tasks, pickHeaderId, opName, getWarehouseId(), getSysUserId());
        } catch (WmsServiceException e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }

    @AutoLog(value = "t_wms_pick_header-pickDOTask", operateType = 5)
    @RequestMapping(value = "/pickDOTask", method = RequestMethod.POST)
    public Result<?> pickDOTask(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<String> pointCodes = new ArrayList<>();
            Long pickHeaderId = param.getLong("pickHeaderId");
            String opName = param.getString("opName");
            String pointCode = Optional.ofNullable(param.getString("pointCode")).orElse("");
            if (StringUtils.isNotEmpty(pointCode)) {
                pointCodes = Arrays.asList(pointCode.split(","));
            }
            List<PickTaskDto> tasks = JSON.parseArray(param.getJSONArray("data").toJSONString(), PickTaskDto.class);
            wmsDeliveryFacade.pickDOPickTask(tasks, pointCodes, pickHeaderId, opName, getWarehouseId(), getSysUserId());
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }
}
